﻿using System;
using UnityEngine;

namespace Core
{
    /// <summary>
    /// 前缀 ipt_XXX InputField
    /// </summary>
    public class UIInputField : UIWidget
    {
        private UnityEngine.UI.InputField ipt1;
        private TMPro.TMP_InputField ipt2;

        public Action<string> OnValueChanged;

        public string text
        {
            get { return ipt1 == null ? ipt2.text : ipt1.text; }
            set
            {
                if (ipt1 != null)
                {
                    ipt1.text = value;
                }

                if (ipt2 != null)
                {
                    ipt2.text = value;
                }
            }
        }

        public void ActivateInputField()
        {
            ipt1?.ActivateInputField();
            ipt2?.ActivateInputField();
        }

        public override void Awake(GameObject go)
        {
            base.Awake(go);

            ipt1 = go.GetComponent<UnityEngine.UI.InputField>();
            ipt1?.onValueChanged.AddListener(OnValueChangedHandler);

            ipt2 = go.GetComponent<TMPro.TMP_InputField>();
            ipt2?.onValueChanged.AddListener(OnValueChangedHandler);
        }

        public override void Dispose()
        {
            if (IsDisposed) return;
            base.Dispose();

            if (ipt1 != null)
            {
                ipt1.onValueChanged.RemoveListener(OnValueChangedHandler);
                ipt1 = null;
            }

            if (ipt2 != null)
            {
                ipt2.onValueChanged.RemoveListener(OnValueChangedHandler);
                ipt2 = null;
            }
        }

        private void OnValueChangedHandler(string arg0)
        {
            OnValueChanged?.Invoke(arg0);
        }
    }
}
